﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using System;

public class ImageItem
{
    public Image _targetImage;
    public Texture2D _targetTexture;
    public Transform _nlodingBar;

    public ImageItem(Texture2D texture,Image image,Transform loadingBar)
    {
        this._targetImage = image;
        this._targetTexture = texture;
        this._nlodingBar = loadingBar;
    }
}

public class PageView : MonoBehaviour, IBeginDragHandler, IEndDragHandler {

    private const string imageItemBg = "kd_bg7";
    private Continent _continent;

    private ScrollRect rect;                        //滑动组件  
    private float targethorizontal = 0;             //滑动的起始坐标  
    private bool isDrag = false;                    //是否拖拽结束  
    private List<float> posList = new List<float> ();            //求出每页的临界角，页索引从0开始  
    private int currentPageIndex = -1;
    private int targetPageIndex = 0;
    public Action<int> OnPageChanged;

    private bool _camInteractive;

    private bool stopMove = true;
    public float smooting = 4;      //滑动速度  
    public float sensitivity = 0;
    private float startTime;

    private Rect selfRect;

    private int photoAmountPerPage = 5;

    private float startDragHorizontal;

    private Dictionary<int, GameObject> _ViewCreatedDic;

    enum GallayTypeSetting { seven,eight}
    private GallayTypeSetting _currentGallarySetting = GallayTypeSetting.eight;

    GameObject template;

    private Queue<ImageItem> _imageLoadQueue;

    private bool isCurrentImageItemLoad;

    private List<GallayImageData> _gallayImgWithCotinent;
    public List<GallayImageData> GallayImgWithContinent
    {
        get {
            return _gallayImgWithCotinent;
        }
        set {
            _gallayImgWithCotinent = value;
        }
    }

    public void Init(List<GallayImageData> gallayImagelist,Continent continent,uint photoid = ExpressConsts.defaultUID)
    {
        this._continent = continent;

        this.targetPageIndex = GetPhotoPageIndex(ref gallayImagelist, photoid) ;
        //Debug.Log("________________________"+targetPageIndex);

        _imageLoadQueue = new Queue<ImageItem>();

        GallayImgWithContinent = gallayImagelist;

        GameObjectPool.Instance.PrepareGameObject(ExpressPath.gridlayoutUIItem, enResourceType.UIPrefab, 30);

        rect = transform.GetComponent<ScrollRect>();

        _ViewCreatedDic = new Dictionary<int, GameObject>();

        selfRect = GetComponent<RectTransform>().rect;
        template = rect.content.transform.GetChild(0).gameObject;
        template.GetComponent<RectTransform>().sizeDelta = new Vector2(selfRect.width, selfRect.height);
        template.SetActive(false);

        ContinentRefresh();
    }

    private int GetPhotoPageIndex(ref List<GallayImageData> list, uint id)
    {
        int pageIndex = 0;
        GallayTypeSetting startSet = _currentGallarySetting;
        for (int i = 0; i < list.Count; i++)
        {
            if (list[i]._id == id)
            {
                pageIndex = GetPageCount(i+1, _currentGallarySetting) - 1;
            }
        }
        _currentGallarySetting = startSet;

        return pageIndex;
    }

    public void Nextpage()
    {
        targetPageIndex++;
        if (targetPageIndex > pageAmount - 1)
        {//翻到了一个大洲页面的尽头
            GallaryPanel.Instance.OnAContinentPageRightOver(this._continent);
        }
        else
        {
            pageTo(targetPageIndex, true);
        }

    }

    public void LastPage()
    {

        targetPageIndex--;
        if (targetPageIndex < 0)
        {
            GallaryPanel.Instance.OnAContinentPageLeftOver(this._continent);
        }
        else
        {
            pageTo(targetPageIndex, true);
        }

    }

    private int GetPageCount(int totalImageCount, GallayTypeSetting currentGallarySetting)
    {
        int index = 0;
        int count = -1; //图片序号是从0开始的
        GallayTypeSetting currentShowtype = currentGallarySetting;
        while (count < totalImageCount)
        {
            count += currentShowtype == GallayTypeSetting.seven ? 7 : 8;
            currentShowtype = currentShowtype == GallayTypeSetting.seven ? GallayTypeSetting.eight : GallayTypeSetting.seven;
            index++;
        }

        return index;
    }

    int pageAmount;
    public void ContinentRefresh()
    {
        //每次切换一个洲初始到第一页
        sum = 0;

        posList.Clear();

        Resources.UnloadUnusedAssets();
        GC.Collect();
        
        foreach (Transform child in rect.content.transform)
        {
            if (child.name != "Template")
            {
                foreach (Transform item in child)
                {
                    if (item.name != "typesetting1" && item.name != "typesetting1")
                    {
                        GameObjectPool.Instance.RecycleGameObject(item.gameObject);
                        item.SetParent(GameObject.Find("GameObjectPool").transform);
                    }
                }
                Destroy(child.gameObject);


            }

        }

        rect = transform.GetComponent<ScrollRect>();

        pageAmount = GetPageCount(GallayImgWithContinent.Count, _currentGallarySetting);
        Debug.Log("pageAmount: " + pageAmount);

        //照片的页数为0,不能交互，显示提示
        if (pageAmount == 0)
        {
            pageAmount = 1;
            _camInteractive = false;
        }
        else
        {
            _camInteractive = true;
        }

        rect.content.sizeDelta = new Vector2(selfRect.width * pageAmount, rect.content.sizeDelta.y);
        float horizontalLength = rect.content.rect.width - selfRect.width;
        posList.Add(0);
        for (int i = 1; i < pageAmount - 1; i++)
        {
            posList.Add(selfRect.width * i / horizontalLength);
        }
        posList.Add(1);

        GallaryPanel.Instance.CreatePageIndexUI(pageAmount);

        pageTo(targetPageIndex, true);

        //刷新一个一个洲记录要重置
        _ViewCreatedDic.Clear();

        Refresh();
    }

    public void Refresh()
    {
        GallaryPanel.Instance.OnPageIndexChange(currentPageIndex);

        //生成相册的页面
        if (pageAmount == 1)
        {//生成第一页
            CreatePageWithIndex(0);
        }
        else if (currentPageIndex == 0)
        {//生成起始两页
            for (int i = 0; i < 2; i++)
            {
                CreatePageWithIndex(i);
            }

        }
        else if (currentPageIndex == pageAmount - 1)
        {//生成后两页
            for (int i = pageAmount -2; i < pageAmount; i++)
            {
                CreatePageWithIndex(i);
            }
        }
        else
        {//生成当前页和前后页
            for (int i = currentPageIndex -1; i <= currentPageIndex +1; i++)
            {
                CreatePageWithIndex(i);
            }
        }

    }

    private int sum;
    private void CreatePageWithIndex(int i)
    {
        if (!_ViewCreatedDic.ContainsKey(i))
        {
            GameObject tempPage = Instantiate<GameObject>(template);
            tempPage.transform.SetParent(rect.content.transform,false);
            tempPage.transform.SetAsLastSibling();
            tempPage.SetActive(true);
            Transform currentTypeSetting = null;
            Transform typesettingAnchor1 = template.transform.Find("typesetting1");
            Transform typesettingAnchor2 = template.transform.Find("typesetting2");


            if (_currentGallarySetting == GallayTypeSetting.eight)
            {
                photoAmountPerPage = 8;
                currentTypeSetting = typesettingAnchor1;
                _currentGallarySetting = GallayTypeSetting.seven;
            }
            else if(_currentGallarySetting == GallayTypeSetting.seven)
            {
                photoAmountPerPage = 7;
                currentTypeSetting = typesettingAnchor2;
                _currentGallarySetting = GallayTypeSetting.eight;
            }


            foreach (Transform anchor in currentTypeSetting)
            {
                int textureIndex = sum;
                sum++;


                if (textureIndex >= GallayImgWithContinent.Count) continue;

                GameObject t = GameObjectPool.Instance.GetGameObject(ExpressPath.gridlayoutUIItem, enResourceType.UIPrefab);
                t.transform.SetParent(tempPage.transform, false);
                t.SetActive(true);
                t.transform.SetPositionAndRotation(anchor.position, anchor.rotation);

                Transform n_texture = t.transform.Find("n_Texture");        //小图
                Transform n_wenhao = t.transform.Find("n_Wenhao");        //问号
                Transform n_loading = t.transform.Find("n_Loading");        //loding图
                //Transform n_star = t.transform.Find("n_Star");              //星星
                n_loading.SetActive(false);         //默认隐藏loding
                n_texture.SetActive(false);
                n_wenhao.SetActive(true);
                //n_star.SetActive(false);        //默认隐藏星星

                Text description = t.transform.Find("TextContainer/Text").GetComponent<Text>(); //描述文字
                t.GetComponent<Button>().enabled = true;
                t.GetComponent<Image>().enabled = true;
                t.GetComponent<Button>().onClick.RemoveAllListeners();
                n_texture.GetComponent<Image>().sprite = UISpriteManager.Instance.GetSprite(emUIAltas.Express_01, imageItemBg);
               

                //需要判断图片状态，决定是否显示和其它的逻辑
                GallayImageData imgdata = GallayImgWithContinent[textureIndex];
                description.text = imgdata._imagename;
                if (imgdata._id == ExpressDataManager.Instance.TotalGallayInfo.lastNewaddPicture)
                {
                    //记录ui位置
                    GallaryPanel.m_current_ui_startposition = UGUITweener.GetCanvasLocalPos(WindowManager.Instance.canvas, t.GetComponent<RectTransform>());
                }

                t.GetComponent<Button>().onClick.AddListener(() =>
                {
                    CommonSound.PlayClick();
                    Sprite gallarytexture = n_texture.GetComponent<Image>().sprite;
                    if (gallarytexture.name.Contains(imageItemBg))
                    {
                        WindowManager.Instance.CloseWindow(WinNames.GallaryPanel,false);
                        StartPanel.Instance.StartTravel();
                    }
                    else
                    {
                        if (gallarytexture != null)
                        {
                            //n_star.SetActive(false);
                            ExpressDataManager.Instance.TotalGallayInfoDic[imgdata._id].isNewAdded = false;
                            ExpressDataManager.Instance.TotalGallayLocalDataSave();
                            GallayPictureShowPanelOpenPara para = new GallayPictureShowPanelOpenPara();
                            para._anchor_startPoint = UGUITweener.GetCanvasLocalPos(WindowManager.Instance.canvas, t.GetComponent<RectTransform>());
                            para._name = imgdata._imagename;
                            para._sprite = gallarytexture;
                            para._pic_id = imgdata._id;
                            WindowManager.Instance.OpenWindow(WinNames.GallayPictureShowPanel, para);
                        }
                        else
                        {
                            //该照片为空，可能未下载完成，或者照片解锁
                        }
                    }
                });
                if (string.IsNullOrEmpty(imgdata._url)) continue;

                description.text = imgdata._imagename;

                n_texture.SetActive(true);
                n_loading.SetActive(true);
                n_wenhao.SetActive(false);
                //n_star.SetActive(false);

                MonoInstane.Instance.StartCoroutine(ExpressDataManager.Instance.LoadTexture(new  ExpressImageLocalloadArg(imgdata._id, imgdata._url, imgdata._imagename), (callback) =>
                {
                    if (callback != null)
                    {
                        Texture2D t2d = callback._tex;
                        if (t2d != null)
                        {
                            if (t != null)
                            {
                                //填充信息
                                Image img = n_texture.GetComponent<Image>();
                                _imageLoadQueue.Enqueue(new ImageItem(t2d, img,n_loading));

                            }
                        }
                    }
                    else
                    {
                       //加载失败
                   }



                }, null));
            }

            _ViewCreatedDic.Add(i, tempPage);

        }
    }

    void Update () {

        if (_imageLoadQueue.Count > 0)
        {
            if (!isCurrentImageItemLoad)
            {
                isCurrentImageItemLoad = true;

                ImageItem item = _imageLoadQueue.Dequeue();

                Texture2D t2d = item._targetTexture;
                Sprite sp = Sprite.Create(t2d, new Rect(0, 0, t2d.width, t2d.height), Vector2.zero);
                item._targetImage.sprite = sp;
                item._nlodingBar.SetActive(false);

                isCurrentImageItemLoad = false;
            }
            
        }

        if (!isDrag && !stopMove) {
            startTime += Time.deltaTime;
            float t = startTime * smooting;
            rect.horizontalNormalizedPosition = Mathf.Lerp (rect.horizontalNormalizedPosition , targethorizontal , t);
            if (t >= 1)
            {
                stopMove = true;
                //动画结束时，说明滚动到了目标页面，定位目标图片的位置
                //EventBus.Instance.BroadCastEvent<Vector3>(EventID.ON_EXPRESS_PIC_INITED,)
            }
              
        }
    }

    private void PageToSmooth(int index)
    {
        targethorizontal = posList[index]; //设置当前坐标，更新函数进行插值  
        isDrag = false;
        startTime = 0;
        stopMove = false;
    }

    public void pageTo (int index,bool smooth = false) {

        if(index >= 0 && index < posList.Count) {
            //切换页面时，清除当前的下载任务
            //DownloadManager.Instance.Init();
            if (smooth)
            {
                PageToSmooth(index);
            }
            else
            {
                rect.horizontalNormalizedPosition = posList[index];
            }
            SetPageIndex(index);

        } else {
            Debug.LogWarning ("页码不存在");
        }
    }
    private void SetPageIndex (int index) {
        if(currentPageIndex != index) {
            currentPageIndex = index;
            if(OnPageChanged != null)
                OnPageChanged (index);

            Refresh();
        }
    }

    public void OnBeginDrag (PointerEventData eventData) {
        if (_camInteractive)
        {
            isDrag = true;
            startDragHorizontal = rect.horizontalNormalizedPosition;
        }
      
    }

    public void OnEndDrag (PointerEventData eventData) {
        if (_camInteractive)
        {
            float posX = rect.horizontalNormalizedPosition;
            posX += ((posX - startDragHorizontal) * sensitivity);
            posX = posX < 1 ? posX : 1;
            posX = posX > 0 ? posX : 0;

            if (pageAmount > 1)
            {
                int index = 0;
                float offset = Mathf.Abs(posList[index] - posX);
                for (int i = 1; i < posList.Count; i++)
                {
                    float temp = Mathf.Abs(posList[i] - posX);
                    if (temp < offset)
                    {
                        index = i;
                        offset = temp;
                    }
                }

                targetPageIndex = index;
                SetPageIndex(targetPageIndex);

                targethorizontal = posList[index]; //设置当前坐标，更新函数进行插值 
            }
            

           
            isDrag = false;
            startTime = 0;
            stopMove = false;
        }
       
    } 
}
